<script setup>
import {ref, onMounted} from 'vue'
import {
  queryStocktaking,
  addStocktaking,
  queryStocktakingById,
  deleteStocktaking,
  updateStocktaking,
  updateLossCount
} from '../../api/stocktaking'
import {queryItemList} from '@/api/item.js'
import {queryWarehousingUpList} from '@/api/warehousingentryup.js'
import {queryAllWarehouseAreaLocal} from '@/api/warehousearealocal.js'
import {ElMessage, ElMessageBox} from 'element-plus'

//定义库位集合
const warehouseAreaLocalList = ref([])
//查询所有库位
const getwarehouseAreaLocalList = async () => {
  const result = await queryAllWarehouseAreaLocal()
  warehouseAreaLocalList.value = result.data
}

//定义表格数据
const stocktakingList = ref([])
//分页条件查询
const query = async () => {
  const result = await queryStocktaking(page.value, pageSize.value, stocktakingFrom.value.id)
  stocktakingList.value = result.data.rows
  total.value = result.data.total
}
//清空表单数据
const clear = () => {
  stocktakingFrom.value = {id: ''}
  query()
}
//定义表单数据
const stocktakingFrom = ref({id: ''})

//定义分页的变量
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
//定义分页的点击事件
const handleSizeChange = (val) => {
  page.value = 1
  query()
}
const handleCurrentChange = (val) => {
  query()
}

//定义对话款数据
const dialogShow = ref(false)
const title = ref('')
const dialogData = ref({
  skuCode: '', skuName: '', skuPrice: '', targetWarehouseName: '', targetWarehouseAreaName: '',
  targetWarehouseAreaLocalCode: '', correctTime: '', bookCount: ''
})


//定义子对话框的数据
const selectDialogShow = ref(false)
const selectForm = ref({skuName: '', spuCode: ''})
const selectableList = ref([])
//查询子表数据
const querySelectable = async () => {
  const result = await queryItemList(pageSelect.value, pageSizeSelect.value, selectForm.value.skuName, selectForm.value.spuCode)
  selectableList.value = result.data.list
  totalSelect.value = result.data.totalSelect
}
//清空子表表单数据
const clearSelectable = () => {
  selectForm.value = {skuName: '', spuCode: ''}
  querySelectable()
}
//定义子表分页数据
const pageSelect = ref(1)
const pageSizeSelect = ref(10)
const totalSelect = ref(0)
const handleSizeSelectChange = (val) => {
  pageSelect.value = 1
  querySelectable()
}
const handleCurrentSelectChange = (val) => {
  querySelectable()
}
//定义商品集合
const selectedItems = ref([])
//获取选中商品的数据
const handleSelectionChange = (value) => {
  selectedItems.value = value
}
//子表中添加商品的数据
const addSelectedItems = () => {
  selectedItems.value.forEach(item => {
    dialogData.value.skuName = item.skuName
    dialogData.value.skuCode = item.spuCode
    dialogData.value.skuPrice = item.skuPrice
    dialogData.value.bookCount = ''
    dialogData.value.correctTime = ''
    dialogData.value.targetWarehouseAreaLocalCode = ''
    dialogData.value.targetWarehouseAreaName = ''
    dialogData.value.targetWarehouseName = ''
  })
  // 关闭选择对话框
  selectDialogShow.value = false
  // 清空选中项
  selectedItems.value = []
  clearSelectable()
}


//仓库对话框数据
const selectWarehouseDialogShow = ref(false)
const selectWarehouseForm = ref({warehouseName: '', skuName: ''})
//定义仓库的数据集合
const selectWarehouseList = ref([])
//定义仓库对话框的分页数据
const pageSelectWarehouse = ref(1)
const pageSizeSelectWarehouse = ref(10)
const totalSelectWarehouse = ref(0)
const handleSizeSelectWarehouseChange = (val) => {
  pageSelectWarehouse.value = 1
  querySelectWarehouseUp()
}
const handleCurrentSelectWarehouseChange = (val) => {
  querySelectWarehouseUp()
}
//查询仓库对话框数据
const querySelectWarehouseUp = async () => {
  const result = await queryWarehousingUpList(pageSelectWarehouse.value, pageSizeSelectWarehouse.value, selectWarehouseForm.value.warehouseName, selectWarehouseForm.value.skuName)
  selectWarehouseList.value = result.data.rows
  totalSelectWarehouse.value = result.data.total
}
//清空仓库对话框数据
const clearSelectWarehouseUp = () => {
  selectWarehouseForm.value = {warehouseName: '', skuName: ''}
  querySelectWarehouseUp()
}

//定义选中仓库的数据
const selectWarehouses = ref([])
//获取选中仓库的数据
const handleSelectionWarehouseChange = (value) => {
  selectWarehouses.value = value
}

//子表中添加商品的数据
const addSelectedWarehouse = () => {
  selectWarehouses.value.forEach(warehouse => {
    dialogData.value.bookCount = warehouse.count
    dialogData.value.targetWarehouseName = warehouse.warehouseName
    dialogData.value.targetWarehouseAreaName = warehouse.warehouseAreaName
    dialogData.value.targetWarehouseAreaLocalCode = warehouse.id
    dialogData.value.skuName = warehouse.skuName
    dialogData.value.skuCode = warehouse.skuCode
    dialogData.value.skuPrice = warehouse.price
    dialogData.value.correctTime = ''
  })
  // 关闭选择对话框
  selectWarehouseDialogShow.value = false
  // 清空选中项
  selectWarehouses.value = []
  clearSelectWarehouseUp()
}

//在选择库位的时候给仓库，和库区填充数据
const handleLocationChange = (selectedId) => {
  // 查找选中的库位信息
  const selectedLocation = warehouseAreaLocalList.value.find(item => item.id == selectedId);
  if (selectedLocation) {
    dialogData.value.targetWarehouseName = selectedLocation.warehouseName
    dialogData.value.targetWarehouseAreaName = selectedLocation.warehouseAreaName
  }
}

//定义盘点数据的弹窗
const selectcorrectCountDialogShow = ref(false)
const selectcorrectCountForm = ref({id: '', bookCount: '', correctCount: ''})
//报损失数据的弹窗
const selectLossCountDialogShow = ref(false)
const selectLossCountForm = ref({id: '', lossCount: '', lossCategory: ''})
//挂载
onMounted(() => {
  query()
  querySelectable()
  querySelectWarehouseUp()
  getwarehouseAreaLocalList()
})

//添加的点击事件
const addstocktaking = () => {
  dialogShow.value = true
  isViewMode.value = false
  title.value = '库存盘点'
  //清空表单数据
  dialogData.value = {
    skuCode: '', skuName: '', skuPrice: '', targetWarehouseName: '', targetWarehouseAreaName: '',
    targetWarehouseAreaLocalCode: '', correctTime: '', bookCount: ''
  }
}

//保存的点击事件
const savedialogData = async () => {
  const result = await addStocktaking(dialogData.value)
  if (result.code) {
    ElMessage.success('操作成功！')
    dialogShow.value = false
    query()
  } else {
    ElMessage.error('操作失败！请重新操作')
  }
}

// 查看模式标志
const isViewMode = ref(false)
//回显数据
const check = async (id) => {
  title.value = '查看盘点数据'
  isViewMode.value = true  // 设置为查看模式
  dialogShow.value = true
  const result = await queryStocktakingById(id)
  dialogData.value = result.data
}

// // 删除
// const deleteById = async (id)=>{
//   const result = await deleteStocktaking(id) 
//   if(result.code){
//     ElMessage.success('操作成功！')
//     query()
//   }else{
//     ElMessage.error('操作失败！请重新操作')
//   }
// }

//删除
const deleteById = async (id) => {
  //弹出一个确认框;
  ElMessageBox.confirm('确认删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const result = await deleteStocktaking(id);
    if (result.code) {
      ElMessage.success('操作成功')
      query()
    } else {
      ElMessage.error('操作失败！请重新操作')
    }
  }).catch(() => {
    // 用户点击取消后的操作
    ElMessage.info('已取消操作')
  })
}

//盘点的点击事件
const confirm = async (row) => {
  selectcorrectCountDialogShow.value = true
  selectcorrectCountForm.value.id = row.id
  selectcorrectCountForm.value.bookCount = row.bookCount
  selectcorrectCountForm.value.correctCount = ''
}

//盘点结果保存的点击事件
const addselectcorrectCount = async () => {
  const result = await updateStocktaking(selectcorrectCountForm.value)
  if (result.code) {
    ElMessage.success('操作成功！')
    //清空表单数据
    selectcorrectCountForm.value = {id: '', bookCount: '', correctCount: ''}
    selectcorrectCountDialogShow.value = false
    query()
  } else {
    ElMessage.error('操作失败！请重新操作')
  }
}

//报损的点击事件
const confirmLossCount = async (row) => {
  selectLossCountDialogShow.value = true
  selectLossCountForm.value.id = row.id
  selectLossCountForm.value.lossCount = Math.abs(row.discrepancyCount)
  selectLossCountForm.value.lossCategory = ''
}
//报损结果保存的点击事件
const addLossCount = async () => {
  const result = await updateLossCount(selectLossCountForm.value)
  if (result.code) {
    ElMessage.success('操作成功！')
    //清空表单数据
    selectLossCountForm.value = {id: '', lossCount: '', lossCategory: ''}
    selectLossCountDialogShow.value = false
    query()
  } else {
    ElMessage.error('操作失败！请重新操作')
  }
}
</script>
<template>
  <div><h3>库存盘点</h3></div>
  <div>
    <el-form :inline="true" :model="stocktakingFrom">
      <el-form-item>
        <el-button type="primary" @click="addstocktaking" plain>
          <el-icon>
            <Plus/>
          </el-icon>
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="stocktakingFrom.id" placeholder="盘点单号" style="width: 200px;"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query" plain>查询</el-button>
        <el-button type="default" @click="clear" plain>清空</el-button>
      </el-form-item>
    </el-form>
  </div>


  <!-- table表格 -->
  <div>
    <el-table :data="stocktakingList" border style="width: 100%">
      <el-table-column fixed type="index" label="序号" align="center" width="80"/>
      <el-table-column prop="id" label="盘点单号" align="center" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 1" type="info">未确认</el-tag>
          <el-tag v-else-if="scope.row.status == 2" type="success">已确认</el-tag>
          <el-tag v-else="scope.row.status == 3" type="danger">已调整</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="skuCode" label="商品编码" align="center" width="150"></el-table-column>
      <el-table-column prop="skuName" label="商品名称" align="center" width="150"></el-table-column>
      <el-table-column prop="warehouseName" label="仓库名称" align="center" width="200"></el-table-column>
      <el-table-column prop="warehouseAreaName" label="库区名称" align="center" width="150"></el-table-column>
      <el-table-column prop="warehouseAreaLocalName" label="库位名称" align="center" width="150"></el-table-column>
      <el-table-column prop="bookCount" label="账面数量" align="center" width="120"></el-table-column>
      <el-table-column prop="correctCount" label="盘点数量" align="center" width="120"></el-table-column>
      <el-table-column prop="discrepancyCount" label="差异数量" align="center" width="120"></el-table-column>
      <el-table-column prop="createBy" label="创建人" align="center" width="120"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="200"></el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="210">
        <template #default="scope">
          <el-button type="success" size="small" @click="check(scope.row.id)" plain>
            <el-icon>
              <View/>
            </el-icon>
          </el-button>
          <el-button type="success" size="small" @click="confirm(scope.row)" plain>
            <el-icon>
              <DocumentChecked/>
            </el-icon>
          </el-button>
          <el-button type="warning" size="small" @click="confirmLossCount(scope.row)" plain>
            <el-icon>
              <DocumentDelete/>
            </el-icon>
          </el-button>
          <el-button type="danger" size="small" @click="deleteById(scope.row.id)" plain>
            <el-icon>
              <Delete/>
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div>
    <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
  </div>


  <!-- 弹出框 -->
  <el-dialog v-model="dialogShow" :title="title" width="400" align-center>
    <el-form :model="dialogData">
      <el-form-item>
        <el-button type="primary" @click="selectDialogShow = true" plain>
          <el-icon>
            <Goods/>
          </el-icon>
        </el-button>
        <el-button type="primary" @click="selectWarehouseDialogShow = true" plain>
          <el-icon>
            <House/>
          </el-icon>
        </el-button>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-input v-model="dialogData.skuCode" placeholder="商品编号" disabled/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-input v-model="dialogData.skuName" placeholder="商品名称" disabled/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-input v-model="dialogData.skuPrice" placeholder="商品价格" disabled/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-input v-model="dialogData.targetWarehouseName" placeholder="所在仓库" disabled/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-input v-model="dialogData.targetWarehouseAreaName" placeholder="所在库区" disabled/>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dialogData.targetWarehouseAreaLocalCode" @change="handleLocationChange"
                   placeholder="所在库位" style="width: 400px;">
          <el-option v-for="item in warehouseAreaLocalList" :label="item.localCode" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dialogData.correctTime" type="date" placeholder="时间" value-format="YYYY-MM-DD"
                        style="width: 400px;"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-input v-model="dialogData.bookCount" placeholder="账面数量"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogShow = false" type="default" plain>取消</el-button>
      <el-button :disabled="isViewMode" type="primary" @click="savedialogData" plain>确定</el-button>
    </template>
  </el-dialog>


  <!-- 选择商品的弹窗 -->
  <el-dialog v-model="selectDialogShow" title="选择商品" width="70%" align-center>
    <el-form :inline="true" @submit.prevent>
      <el-form-item>
        <el-input v-model="selectForm.skuName" placeholder="商品名称" style="width: 200px;"/>
      </el-form-item>
      <el-form-item>
        <el-input v-model="selectForm.spuCode" placeholder="商品编码" style="width: 200px;"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="querySelectable" plain>查询</el-button>
        <el-button type="default" @click="clearSelectable" plain>清空</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="selectableList" @selection-change="handleSelectionChange" style="margin-top: 10px;" border
              height="300">
      <el-table-column type="selection" width="55"/>
      <el-table-column fixed type="index" label="序号" align="center"/>
      <el-table-column prop="spuCode" label="商品编号" align="center"/>
      <el-table-column prop="skuName" label="商品名称" align="center"/>
      <el-table-column prop="skuPrice" label="商品价格" align="center"/>
      <el-table-column prop="supplierName" label="供应商名称" align="center"/>
      <el-table-column prop="brandName" label="品牌" align="center"/>
    </el-table>

    <!-- 分页 -->
    <div>
      <el-pagination
          v-model:current-page="pageSelect"
          v-model:page-size="pageSizeSelect"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSelect"
          @size-change="handleSizeSelectChange"
          @current-change="handleCurrentSelectChange"/>
    </div>
    <template #footer>
      <el-button @click="selectDialogShow = false">取消</el-button>
      <el-button type="primary" @click="addSelectedItems" plain>添加</el-button>
    </template>
  </el-dialog>


  <!-- 选择仓库里面的商品的弹窗 -->
  <el-dialog v-model="selectWarehouseDialogShow" title="选择仓库里的商品" width="70%" align-center>
    <el-form :inline="true" @submit.prevent>
      <el-form-item>
        <el-input v-model="selectWarehouseForm.warehouseName" placeholder="仓库名称" style="width: 200px;"/>
      </el-form-item>
      <el-form-item>
        <el-input v-model="selectWarehouseForm.skuName" placeholder="商品名称" style="width: 200px;"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="querySelectWarehouseUp" plain>查询</el-button>
        <el-button type="default" @click="clearSelectWarehouseUp" plain>清空</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="selectWarehouseList" @selection-change="handleSelectionWarehouseChange" style="margin-top: 10px;"
              border height="300">
      <el-table-column type="selection" width="55"/>
      <el-table-column fixed type="index" label="序号" align="center"/>
      <el-table-column prop="warehouseName" label="仓库名称" align="center"/>
      <el-table-column prop="warehouseAreaName" label="库区名称" align="center"/>
      <el-table-column prop="warehouseAreaLocalCode" label="库位编号" align="center"/>
      <el-table-column prop="skuName" label="商品名称" align="center"/>
      <el-table-column prop="skuCode" label="商品编号" align="center"/>
      <el-table-column prop="price" label="商品价格" align="center"/>
      <el-table-column prop="count" label="可用数量" align="center"/>
      <el-table-column prop="consignorName" label="货主名称" align="center"/>
    </el-table>

    <!-- 分页 -->
    <div>
      <el-pagination
          v-model:current-page="pageSelectWarehouse"
          v-model:page-size="pageSizeSelectWarehouse"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSelectWarehouse"
          @size-change="handleSizeSelectWarehouseChange"
          @current-change="handleCurrentSelectWarehouseChange"/>
    </div>
    <template #footer>
      <el-button @click="selectWarehouseDialogShow = false">取消</el-button>
      <el-button type="primary" @click="addSelectedWarehouse" plain>添加</el-button>
    </template>
  </el-dialog>


  <!-- 盘点数据的弹窗 -->
  <el-dialog v-model="selectcorrectCountDialogShow" title="输入盘点数量" width="250" align-center>
    <el-form @submit.prevent>
      <el-form-item>
        <el-input v-model="selectcorrectCountForm.bookCount" placeholder="账面数量" style="width: 200px;" disabled/>
      </el-form-item>
      <el-form-item>
        <el-input v-model="selectcorrectCountForm.correctCount" placeholder="盘点数量" style="width: 200px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="selectcorrectCountDialogShow = false">取消</el-button>
      <el-button type="primary" @click="addselectcorrectCount" plain>确定</el-button>
    </template>
  </el-dialog>

  <!-- 报损失数据的弹窗 -->
  <el-dialog v-model="selectLossCountDialogShow" title="报损数据" width="250" align-center>
    <el-form @submit.prevent>
      <el-form-item>
        <el-input v-model="selectLossCountForm.lossCount" placeholder="损失数量" style="width: 200px;" disabled/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-select v-model="selectLossCountForm.lossCategory" placeholder="损失类型" style="width: 200px;">
          <el-option label="破损" value="1"/>
          <el-option label="丢失" value="2"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="selectLossCountDialogShow = false">取消</el-button>
      <el-button type="primary" @click="addLossCount" plain>确定</el-button>
    </template>
  </el-dialog>
</template>
<style scoped>
</style>